import devices from "current-device";
import React, { useContext, useEffect, useState } from "react";

export namespace Devices {
  export const inst = devices;
  const gen_ctx_value = () => ({
    mobile: inst.mobile(),
    tablet: inst.tablet(),
    desktop: inst.desktop(),
    ios: inst.ios(),
    ipad: inst.ipad(),
    iphone: inst.iphone(),
    ipod: inst.ipod(),
    android: inst.android(),
    androidPhone: inst.androidPhone(),
    androidTablet: inst.androidTablet(),
    blackberry: inst.blackberry(),
    blackberryPhone: inst.blackberryPhone(),
    blackberryTablet: inst.blackberryTablet(),
    windows: inst.windows(),
    windowsPhone: inst.windowsPhone(),
    windowsTablet: inst.windowsTablet(),
    fxos: inst.fxos(),
    fxosPhone: inst.fxosPhone(),
    fxosTablet: inst.fxosTablet(),
    meego: inst.meego(),
    television: inst.television(),
    landscape: inst.landscape(),
    portrait: inst.portrait(),
    type: inst.type,
    orientation: inst.orientation,
    os: inst.os
  })
  const ctx = React.createContext(gen_ctx_value());

  export const use = () => useContext(ctx)

  export function Provider(props: React.PropsWithChildren) {
    const [value, set_value] = useState(gen_ctx_value)
    useEffect(() => {
      const ele = document.getElementsByTagName('html').item(0);
      if (!ele) return;
      const ob = new MutationObserver(() => set_value(gen_ctx_value()))
      ob.observe(ele, { attributeFilter: ['class'] })
      return () => ob.disconnect();
    }, [])
    return <ctx.Provider {...props} value={value} />
  }
}
export default Devices;